package Server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Iterator;
import java.util.LinkedList;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

import General.ShipQuoterServiceInterface;
import General.SubServerServiceInterface;

public class SubServerService extends UnicastRemoteObject implements SubServerServiceInterface {
	
	private static final long serialVersionUID = 1L;
	private LinkedList<ShipQuoterServiceInterface> fSubServers;
	private int fNextServerNr = 1;
	
	public SubServerService() throws RemoteException {
		super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory(null, null, true));
		fSubServers = new LinkedList<ShipQuoterServiceInterface>();
	}

	public boolean register(ShipQuoterServiceInterface subServer) throws RemoteException {
		fSubServers.add(subServer);
		System.out.println("[SERVER] Subserver connected to server");
		return true;
	}
	
	public ShipQuoterServiceInterface getNextServer() {
		int returnServerId = fNextServerNr;
		if (fNextServerNr == fSubServers.size()) {
			fNextServerNr = 1;
		} else {
			fNextServerNr++;
		}
		return fSubServers.get(returnServerId-1);
	}
	
	public void changeRate(int shippingType, int rate) {
		Iterator<ShipQuoterServiceInterface> it = fSubServers.iterator();
		while (it.hasNext()) {
			try {
				it.next().changeRate(shippingType, rate);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	public int getNrServers() {
		return fSubServers.size();
	}
	
	public ShipQuoterServiceInterface getServer(int serverNr) {
		return fSubServers.get(serverNr-1);
	}
}
